package com.czh.springboot04.MyController;

import com.czh.springboot04.entity.Question;
import com.czh.springboot04.service.QuestionService;
import com.czh.springboot04.util.R;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/question")
public class QuestionController {
    @Autowired
    private QuestionService questionService;
    @PostMapping("/add")
    public R addQuestion(@RequestBody Question question) {
        Date date = new Date();
//        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
        //System.out.println(formatter.format(date));
        question.setCreateTime(date);

        int i = questionService.addQuestion(question);
        //System.out.println(i);
        if(i> 0 ){
            return R.ok(question);
        }else {
            return R.fail("添加失败");
        }
    }
    @PutMapping("/update")
    public R updateQuestion(@RequestBody Question question) {
        int i = questionService.updateQuestion(question);
        if(i> 0 ){
            return R.ok(question);
        }else {
            return R.fail("修改失败");
        }
    }
    @DeleteMapping("/{id}")
    public R deleteQuestion(@PathVariable int id) {
        int i = questionService.deleteQuestion(id);
        if(i> 0 ){
            return R.ok("删除成功");
        }else {
            return R.fail("失败");
        }
    }
    @GetMapping("/findAll")
    public R findAll(@RequestParam(required = false,defaultValue = "1")int pageNum,
                     @RequestParam(required = false,defaultValue = "3")int pageSize) {
        PageInfo<Question> pageInfo= questionService.findAll(pageNum,pageSize);
        return R.ok(pageInfo);
    }
    @GetMapping("/findByAll")
    public R findByAll(@RequestParam(required = false,defaultValue = "1")int pageNum,
                     @RequestParam(required = false,defaultValue = "3")int pageSize) {
        PageInfo<Question> pageInfo= questionService.findByAll(pageNum,pageSize);
        return R.ok(pageInfo);
    }
    @GetMapping("/{id}")
    public R findById(@PathVariable int id) {
        List<Question> questions = questionService.findById(id);
        return R.ok(questions);
    }
}
